package com.example.demo.bizhan.framework;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static java.lang.System.*;

/**
 * @description: xxx
 * @time: 2020/10/27 15:30
 * @author: baojinlong
 **/
public class ToolUtils {
    public static String getTable(Class<?> clazz) {
        PkBeanAnnotation annotation = clazz.getAnnotation(PkBeanAnnotation.class);
        boolean annotationPresent = clazz.isAnnotationPresent(PkBeanAnnotation.class);
        if (annotationPresent) {
            // 如果存在注解
            return annotation.value();
        } else {
            return clazz.getSimpleName();
        }
    }

    public static String getColumnName(Field field) {
        PkFieldAnnotation annotation = field.getAnnotation(PkFieldAnnotation.class);
        if (annotation != null) {
            return annotation.value();
        } else {
            return field.getName();
        }
    }

    public static void main(String[] args) throws Exception {
        out.println(getTable(ToolUtils.class));
        out.println(getTable(User.class));
        Class<?> aClass = Class.forName("com.example.demo.bizhan.framework.User");
        Field birthday = aClass.getDeclaredField("name");
        out.println(getColumnName(birthday));
        out.println(getMethod(birthday));
    }

    public static Connection getConnection() {
        String url = "jdbc:mysql://localhost:3306/interview";
        String user = "root";
        String pwd = "root";
        try {
            // Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'.
            // The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
            //  Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            out.println("获取mysql连接异常");
        }
        return null;
    }

    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                out.println("关闭连接异常");
            }
        }
    }

    public static String getMethod(Field field) {
        // 获取字段名称
        String fieldName = field.getName();
        return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }
}
